#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

String ssid = "dayuan";
String pswd = "19900625";

// http://api.seniverse.com/v3/weather/daily.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c&start=0&days=5
String api_baseurl = "http://api.seniverse.com/v3/weather/daily.json?key=";
String city = "ningbo";
String api_key = "SHKKV2TxZ6S69CgZN";
String api_url = api_baseurl + api_key + "&location=" + city + "&language=zh-Hans&unit=c&start=0";

void setup()
{
  Serial.begin(9600);

  // 连接wifi
  Serial.print("\n开始连接wifi：");
  Serial.println(ssid);
  WiFi.begin(ssid, pswd);
  unsigned long startTime = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000)
  { // wifi连接中
    delay(500);
    Serial.print(".");
  }

  if (WiFi.status() == WL_CONNECTED) // wifi连接成功
  {
    Serial.println("\nWiFi  连接成功！");

    HTTPClient http;
    WiFiClient socket;
    if (http.begin(socket, api_url)) // 访问api接口地址,注意这个代码只能访问http,不能访问https
    {
      String payload = http.getString();
      Serial.println(payload);

      int httpCode = http.GET();
      Serial.printf("\nHTTP  状态码: %d\n", httpCode);
      if (httpCode == HTTP_CODE_OK)
      {
        String payload = http.getString();
        Serial.println(payload);

        //解析获得的json数据
        JsonDocument doc;
        DeserializationError error = deserializeJson(doc, payload);
        if (error)
        {
          Serial.print(F("\ndeserializeJson() failed: "));
          Serial.println(error.f_str());
          return;
        }
        String temperature= doc["results"][0]["daily"][0]["high"]; //今天最高温度
        String humidity= doc["results"][0]["daily"][0]["humidity"]; //今天湿度
        String weather= doc["results"][0]["daily"][0]["text_day"]; //今天天气
        Serial.println("Data Reveived:");
        Serial.println(temperature);
        Serial.println(humidity);
        Serial.println(weather);

      }
      http.end(); // 释放资源
    }
    else{
      Serial.println("HTTP 请求失败！");
    }
  }
  else
  {
    Serial.println("WiFi  连接失败！");
  }
}

void loop()
{
}